package ott.adapter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import oot.data.Connection;
import oot.data.JSonPaser;
import oot.data.User;
import oot.tab.activity.R;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class UserAdapter extends ArrayAdapter<User> implements Filterable {
	private ArrayList<User> filteredModelItemsArray;
	private ArrayList<User> allModelItemsArray;
	private LayoutInflater mInflater;
	private ModelFilter filter;
	int layoutResourceId;
	private Context mContext;

	public UserAdapter(Context context, int viewResourceId,
			ArrayList<User> contents) {
		super(context, 0);
		this.mContext = context;
		this.allModelItemsArray = new ArrayList<User>();
		allModelItemsArray.addAll(contents);
		this.filteredModelItemsArray = new ArrayList<User>();
		filteredModelItemsArray.addAll(allModelItemsArray);
		this.layoutResourceId = viewResourceId;
		mInflater = LayoutInflater.from(context);
		// setDropDownViewResource(viewResourceId);
		getFilter();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		// Log.i("test","adapter view");
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = mInflater.inflate(layoutResourceId, null);

			holder.userId = (TextView) convertView
					.findViewById(oot.tab.activity.R.id.tv_user_row_screen_name);
			holder.userScreenName = (TextView) convertView
					.findViewById(oot.tab.activity.R.id.tv_user_row_userid);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		Log.d("test", "image url avatar"+Connection.BASE_URL_IMAGE+filteredModelItemsArray.get(position).getUserAvatarURL());
		AQuery a = new AQuery(mContext);
		a.id(R.id.img_user_row_avata)
				.visible()
				.image(Connection.BASE_URL_IMAGE+filteredModelItemsArray.get(position).getUserAvatarURL(),
						true, true, 20, R.drawable.m05_item_avar);
		holder.userId.setText(filteredModelItemsArray.get(position)
				.getUserName());
		holder.userScreenName.setText(filteredModelItemsArray.get(position)
				.getUserScreenName());
		return convertView;
	}

	public Filter getFilter() {
		if (filter == null) {
			filter = new ModelFilter();
		}
		return filter;
	}

	private class ModelFilter extends Filter {
		private Object lock;

		@Override
		protected FilterResults performFiltering(CharSequence constraint) {
			FilterResults result = new FilterResults();
			lock = new Object();
			final RequestParams requestParams = new RequestParams();
			if (constraint != null && constraint.toString().length() > 0) {
				Log.i("test", "run to filter");
				requestParams.put("name", constraint.toString());
				constraint = constraint.toString().toLowerCase();
				final ArrayList<User> filteredItems = new ArrayList<User>();
				Thread t = new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						Connection.post("users/suggestByName", requestParams,
								new AsyncHttpResponseHandler() {
									@Override
									public void onSuccess(String res) {
										// TODO Auto-generated method stub
										try {
											JSONObject jsonObject = new JSONObject(
													res);
											if (jsonObject
													.getInt("status_code") == 0) {
												JSONArray jsonArray = jsonObject
														.getJSONArray("entity");
												for (int i = 0; i < jsonArray
														.length(); i++) {
													User user = new User();
													user = JSonPaser
															.paserUser(jsonArray
																	.getJSONObject(
																			i)
																	.getJSONObject(
																			"User"));
												filteredItems.add(user);
												}
											}
										} catch (JSONException j) {
											j.printStackTrace();
										}
										synchronized (lock) {
											lock.notifyAll();
										}
									}
								});
					}
				});
				t.start();

				synchronized (lock) {
					try {
						lock.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				//lock = false;
				result.count = filteredItems.size();
				result.values = filteredItems;
			} else {
				synchronized (this) {
					result.values = allModelItemsArray;
					result.count = allModelItemsArray.size();
				}
			}
			return result;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected void publishResults(CharSequence constraint,
				FilterResults results) {
			// Log.i()
			filteredModelItemsArray = (ArrayList<User>) results.values;
			notifyDataSetChanged();
			clear();
			for (int i = 0, l = filteredModelItemsArray.size(); i < l; i++)
				add(filteredModelItemsArray.get(i));
			notifyDataSetInvalidated();
		}
	}

	private class ViewHolder {
		TextView userId;
		TextView userScreenName;
	}

}
